<template>
  <div class="device-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">设备管理</h1>
        <p class="page-description">管理所有智能音频设备，查看设备状态及用户关联信息</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="showAddDeviceDialog" size="large">
          <el-icon><Plus /></el-icon> 添加设备
        </el-button>
        <el-button type="success" @click="exportDeviceData" size="large">
          <el-icon><Download /></el-icon> 导出设备列表
        </el-button>
      </div>
    </div>

    <!-- 设备列表卡片 -->
    <div class="row-container">
      <el-card class="content-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">设备列表</span>
            <div class="card-actions">
              <el-input
                v-model="searchQuery"
                placeholder="搜索设备ID或用户名"
                clearable
                @clear="resetSearch"
                @input="handleSearch"
                style="width: 250px"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </template>
        
        <el-table 
          v-if="!loading" 
          :data="filteredDeviceList" 
          border 
          style="width: 100%" 
          :row-class-name="getRowClass"
          :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: '600'}"
        >
          <el-table-column prop="device_id" label="设备ID" width="180"></el-table-column>
          <el-table-column label="设备状态" width="120">
            <template #default="scope">
              <el-tag :type="!scope.row.is_activated ? 'info' : 'success'" effect="dark">
                {{ !scope.row.is_activated ? '未激活' : '已激活' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="用户信息" width="180">
            <template #default="scope">
              <span :class="{ 'inactive-text': !scope.row.is_activated }">
                {{ scope.row.user ? scope.row.user.user_name : '未分配' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="音频模式">
            <template #default="scope">
              <span :class="{ 'inactive-text': !scope.row.is_activated }">
                {{ scope.row.status && scope.row.status.audio ? scope.row.status.audio.mode : '未知' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="音效">
            <template #default="scope">
              <span :class="{ 'inactive-text': !scope.row.is_activated }">
                {{ scope.row.status && scope.row.status.audio ? scope.row.status.audio.effect : '未知' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="电源状态">
            <template #default="scope">
              <template v-if="!scope.row.is_activated">
                <el-tag type="info">未激活</el-tag>
              </template>
              <template v-else>
                <el-tag :type="scope.row.status && scope.row.status.power && scope.row.status.power.state === 'ON' ? 'success' : 'danger'">
                  {{ scope.row.status && scope.row.status.power ? scope.row.status.power.state : '未知' }}
                </el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="电池电量">
            <template #default="scope">
              <template v-if="!scope.row.is_activated">
                <span class="inactive-text">未激活</span>
              </template>
              <template v-else>
                <el-progress 
                  :percentage="scope.row.status && scope.row.status.power ? scope.row.status.power.battery_level : 0"
                  :status="getBatteryStatus(scope.row.status && scope.row.status.power ? scope.row.status.power.battery_level : 0)">
                </el-progress>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="网络状态">
            <template #default="scope">
              <template v-if="!scope.row.is_activated">
                <el-tag type="info">未激活</el-tag>
              </template>
              <template v-else>
                <el-tag :type="scope.row.status && scope.row.status.network && scope.row.status.network.wifi_state === 'Connected' ? 'success' : 'warning'">
                  {{ scope.row.status && scope.row.status.network ? scope.row.status.network.wifi_state : '未知' }}
                </el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="create_at" label="创建时间"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button size="small" type="danger" @click="deleteDevice(scope.row)" class="action-button">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-skeleton v-else :rows="8" animated style="margin: 20px 0" />
        
        <div class="pagination" v-if="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </el-card>
    </div>
    
    <!-- 添加设备对话框 -->
    <el-dialog title="添加设备" v-model="addDeviceDialogVisible" width="30%" custom-class="custom-dialog">
      <el-form :model="addDeviceForm" :rules="addDeviceRules" ref="addDeviceFormRef" label-width="100px">
        <el-form-item label="设备ID" prop="device_id">
          <el-input v-model="addDeviceForm.device_id" placeholder="请输入设备ID">
            <template #append>
              <el-button @click="generateDeviceId">生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="设备密钥" prop="device_secret">
          <el-input v-model="addDeviceForm.device_secret" placeholder="请输入设备密钥">
            <template #append>
              <el-button @click="generateDeviceSecret">生成</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDeviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddDevice" :loading="addDeviceLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 页面浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="refreshDeviceList" :loading="loading" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>
  </div>
</template>

<script>
import axios from 'axios'
import { Plus, Download, Delete, RefreshRight, Search } from '@element-plus/icons-vue'

export default {
  name: 'DevicePage',
  components: {
    Plus,
    Download,
    Delete,
    RefreshRight,
    Search
  },
  data() {
    return {
      deviceList: [],
      filteredDeviceList: [], // 用于搜索功能
      searchQuery: '',
      pagination: null,
      loading: false,
      currentPage: 1,
      pageSize: 10,
      // 添加设备相关数据
      addDeviceDialogVisible: false,
      addDeviceLoading: false,
      addDeviceForm: {
        device_id: '',
        device_secret: ''
      },
      addDeviceRules: {
        device_id: [
          { required: true, message: '请输入设备ID', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        device_secret: [
          { required: true, message: '请输入设备密钥', trigger: 'blur' },
          { min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchDevices()
  },
  mounted() {
    // 更完善的 ResizeObserver 错误处理
    window.addEventListener('error', (event) => {
      if (event.message && event.message.includes('ResizeObserver loop')) {
        event.stopImmediatePropagation();
        event.preventDefault();
        console.warn('ResizeObserver 错误已被拦截');
      }
    }, true);
    
    // 也可以拦截未处理的 Promise 错误
    window.addEventListener('unhandledrejection', (event) => {
      if (event.reason && event.reason.message && event.reason.message.includes('ResizeObserver loop')) {
        event.preventDefault();
        console.warn('ResizeObserver Promise 错误已被拦截');
      }
    });
  },
  methods: {
    fetchDevices() {
      this.loading = true;
      axios.get(`https://smartsound.top/api/v1/admin/devices?size=${this.pageSize}&page=${this.currentPage}`)
        .then(response => {
          if (response.data.code === 0) {
            this.deviceList = response.data.data.devices;
            this.filteredDeviceList = [...this.deviceList]; // 初始化过滤列表
            this.pagination = {
              page: response.data.data.page,
              size: response.data.data.size,
              total: response.data.data.total,
              total_pages: response.data.data.total_pages
            };
          } else {
            this.$message.error(response.data.message || '获取设备列表失败');
          }
        })
        .catch(error => {
          console.error('获取设备列表出错:', error);
          this.$message.error('获取设备列表失败，请检查网络连接');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    refreshDeviceList() {
      this.fetchDevices();
    },
    
    handleSearch() {
      if (!this.searchQuery) {
        this.filteredDeviceList = [...this.deviceList];
        return;
      }
      
      const query = this.searchQuery.toLowerCase();
      this.filteredDeviceList = this.deviceList.filter(device => {
        return device.device_id.toLowerCase().includes(query) || 
               (device.user && device.user.user_name.toLowerCase().includes(query));
      });
    },
    
    resetSearch() {
      this.searchQuery = '';
      this.filteredDeviceList = [...this.deviceList];
    },
    
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchDevices()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchDevices()
    },
    getBatteryStatus(level) {
      if (level < 20) return 'exception'
      if (level < 50) return 'warning'
      return 'success'
    },
    
    // 显示添加设备对话框
    showAddDeviceDialog() {
      this.addDeviceDialogVisible = true
      // 重置表单
      if (this.$refs.addDeviceFormRef) {
        this.$refs.addDeviceFormRef.resetFields()
      }
      // 自动生成设备ID和密钥
      this.generateDeviceId()
      this.generateDeviceSecret()
    },
    
    // 生成随机设备ID
    generateDeviceId() {
      const prefix = 'SS'
      const timestamp = new Date().getTime().toString().slice(-8)
      const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
      this.addDeviceForm.device_id = `${prefix}${timestamp}${random}`
    },
    
    // 生成随机设备密钥
    generateDeviceSecret() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let secret = ''
      for (let i = 0; i < 16; i++) {
        secret += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      this.addDeviceForm.device_secret = secret
    },
    
    // 提交添加设备
    submitAddDevice() {
      this.$refs.addDeviceFormRef.validate(valid => {
        if (valid) {
          this.addDeviceLoading = true
          
          // 调用添加设备API - 修改为POST请求，添加device_secret参数
          axios.post(`https://smartsound.top/api/v1/admin/adddevices?device_id=${this.addDeviceForm.device_id}&device_secret=${this.addDeviceForm.device_secret}`)
            .then(response => {
              if (response.data.code === 0) {
                // 添加成功
                this.$message.success(response.data.message || '添加设备成功')
                
                // 关闭对话框
                this.addDeviceDialogVisible = false
                
                // 刷新设备列表
                this.fetchDevices()
              } else {
                // 添加失败
                this.$message.error(response.data.message || '添加设备失败')
              }
            })
            .catch(error => {
              console.error('添加设备出错:', error)
              this.$message.error('添加设备失败，请检查网络连接')
            })
            .finally(() => {
              this.addDeviceLoading = false
            })
        }
      })
    },
    
    // 删除设备
    deleteDevice(device) {
      this.$confirm(`确定要删除设备 ${device.device_id} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除设备API - 修改为DELETE请求
        axios.delete(`https://smartsound.top/api/v1/admin/deletedevices?device_id=${device.device_id}`)
          .then(response => {
            if (response.data.code === 0) {
              // 删除成功
              this.$message.success(response.data.message || '删除设备成功')
              
              // 刷新设备列表
              this.fetchDevices()
            } else {
              // 删除失败
              this.$message.error(response.data.message || '删除设备失败')
            }
          })
          .catch(error => {
            console.error('删除设备出错:', error)
            this.$message.error('删除设备失败，请检查网络连接')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 导出设备数据
    exportDeviceData() {
      this.loading = true;
      // 获取所有设备数据（不分页）
      axios.get(`https://smartsound.top/api/v1/admin/devices?size=1000&page=1`)
        .then(response => {
          if (response.data.code === 0 && response.data.data.devices) {
            const devices = response.data.data.devices;
            this.downloadCSV(devices);
            this.$message.success('设备数据导出成功');
          } else {
            this.$message.error(response.data.message || '导出设备数据失败');
          }
        })
        .catch(error => {
          console.error('导出设备数据出错:', error);
          this.$message.error('导出设备数据失败，请检查网络连接');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 下载CSV文件
    downloadCSV(devices) {
      // 定义CSV表头
      const headers = ['设备ID', '激活状态', '用户信息', '音频模式', '音效', '电源状态', '电池电量', '网络状态', '创建时间'];
      
      // 将设备数据转换为CSV行
      const rows = devices.map(device => [
        device.device_id,
        device.is_activated ? '已激活' : '未激活',
        device.user ? device.user.user_name : '未分配',
        device.status && device.status.audio ? device.status.audio.mode : '未知',
        device.status && device.status.audio ? device.status.audio.effect : '未知',
        device.status && device.status.power ? device.status.power.state : '未知',
        device.status && device.status.power ? device.status.power.battery_level + '%' : '未知',
        device.status && device.status.network ? device.status.network.wifi_state : '未知',
        device.create_at || ''
      ]);
      
      // 组合表头和数据行
      const csvContent = [
        headers.join(','),
        ...rows.map(row => row.join(','))
      ].join('\n');
      
      // 创建Blob对象
      const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
      
      // 创建下载链接
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      
      // 设置下载属性
      const now = new Date();
      const dateStr = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`;
      const timeStr = `${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
      
      link.href = url;
      link.setAttribute('download', `设备数据_${dateStr}_${timeStr}.csv`);
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
    getRowClass({ row }) {
      return !row.is_activated ? 'inactive-device-row' : '';
    }
  }
}
</script>

<style scoped>
.device-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.header-content {
  z-index: 1;
}

.page-title {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.page-actions {
  z-index: 1;
  display: flex;
  gap: 10px;
}

/* 卡片样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

.content-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
}

.content-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 12px;
}

.card-actions {
  display: flex;
  align-items: center;
}

/* 表格样式 */
.el-table {
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
}

.inactive-device-row {
  background-color: #f5f7fa;
  opacity: 0.8;
}

.inactive-text {
  color: #909399;
  font-style: italic;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-button {
  padding: 6px 12px;
}

/* 自定义对话框样式 */
.custom-dialog .el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.custom-dialog .el-dialog__body {
  padding: 20px;
}

.custom-dialog .el-dialog__footer {
  padding: 10px 20px 15px;
  border-top: 1px solid #ebeef5;
}

/* 浮动操作区 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  margin-left: 0;
}

/* 底部安全区域 */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 24px;
  }
  
  .page-actions {
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }
}
</style>